package cn.javabb.api;

import cn.hutool.core.util.StrUtil;
import cn.javabb.common.model.ResponseModel;
import cn.javabb.core.base.BaseController;
import cn.javabb.core.constant.Constant;
import cn.javabb.core.entity.sys.UserAuthDO;
import cn.javabb.core.entity.sys.UserDO;
import cn.javabb.core.service.sys.UserAuthService;
import cn.javabb.core.service.sys.UserService;
import cn.javabb.core.util.EndecryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserApiController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserAuthService userAuthService;
    /**
     * 修改密码
     **/
    @ResponseBody
    @PostMapping("/updatePwd")
    @RequiresAuthentication
    public Object updatePwd(String oldPsw, String newPsw) {
        /*if ("admin".equals(ShiroUtil.getLoginUser().getUserName())) {
            return ResponseModel.Failure("演示账号admin关闭该功能");
        }*/
        //
        UserDO loginUser = getLoginUser();
        String finalSecret = EndecryptUtil.encrytMd5(oldPsw);
        UserDO oldUser = userService.queryById(loginUser.getId());
        UserAuthDO userAuthDO = userAuthService.getUserAuth(loginUser.getId(), Constant.USER_AUTH_ACCOUNT);
        if (null == userAuthDO && StrUtil.isBlank(userAuthDO.getAuthPwd())) {
            return ResponseModel.Failure("无法获取用户密码");
        }
        if (!finalSecret.equals(userAuthDO.getAuthPwd())) {
            return ResponseModel.Failure("原密码输入不正确");
        }
        int num;

        UserAuthDO ua = new UserAuthDO()
                .setId(userAuthDO.getId())
                .setUserId(loginUser.getId())
                .setAuthType(Constant.USER_AUTH_ACCOUNT)
                .setAuthPwd(EndecryptUtil.encrytMd5(newPsw))
                ;
        num = userAuthService.updateSelective(ua);
        if(num>0){
            /*// 获取当前的Subject
            Subject newUser = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(loginUser.getUserName(), user.getUserPwd());
            try {
                log.info("对用户[" + loginUser.getUserName() + "]进行重新登陆验证..验证开始");
                newUser.login(token);
                log.info("对用户[" +  loginUser.getUserName()  + "]进行登录验证..验证通过");
            } catch (IncorrectCredentialsException ice) {
                return ResponseModel.Failure("重新登陆失败");
            }*/
            return ResponseModel.Success("修改成功，用户已重新登陆");
        } else {
            return ResponseModel.Failure("修改失败");
        }
    }
}
